<template>
  <div id="register">
    <nav-bar>
      <template v-slot:default>新用户注册</template>
    </nav-bar>

    <div class="form">
      <van-form @submit="onSubmit">
        <van-field
          v-model="name"
          name="用户名"
          label="用户名"
          placeholder="用户名"
          :rules="[{ required: true, message: '请填写用户名' }]"
        />
        <van-field
          v-model="email"
          name="邮箱"
          label="邮箱"
          placeholder="邮箱"
          :rules="[{ required: true, message: '请填写正确的邮箱' }]"
        />
        <van-field
          v-model="password"
          type="password"
          name="密码"
          label="密码"
          placeholder="密码"
          :rules="[{ required: true, message: '请填写密码' }]"
        />
        <van-field
          v-model="password_confirmation"
          type="password"
          name="确认密码"
          label="确认密码"
          placeholder="确认密码"
          :rules="[{ required: true, message: '请填写一致的密码' }]"
        />
        <div class="link-login" @click="$router.push({ path: '/login' })">
          已有账号，立即登录
        </div>
        <div style="margin: 16px">
          <van-button
            round
            block
            type="info"
            native-type="submit"
            color="#44b883"
            >注册</van-button
          >
        </div>
      </van-form>
    </div>
  </div>
</template>

<script>
import NavBar from "components/common/navbar/NavBar";
import { register } from "network/user";
import { Notify, Toast } from "vant";
import { useRouter } from "vue-router";
import { ref, reactive, toRefs } from "vue";

export default {
  name: "Register",
  setup() {
    const router = useRouter();
    const userinfo = reactive({
      name: "",
      email: "",
      password: "",
      password_confirmation: "",
    });
    const onSubmit = () => {
      // 先验证
      if (userinfo.password != userinfo.password_confirmation) {
        Notify("密码不一致");
      } else {
        // 提交给服务器
        // myaccount123@abc.com qwe123456
        register(userinfo).then((res) => {
          if (res.status == "201") {
            Toast.success("注册成功");

            setTimeout(() => {
              router.push({ path: "/login" });
            }, 1000);
          }
        });

        userinfo.password = "";
        userinfo.password_confirmation = "";
      }
    };

    return { ...toRefs(userinfo), onSubmit };
  },
  components: {
    NavBar,
  },
};
</script>

<style scoped lang="scss">
.form {
  margin-top: 100px;
  .link-login {
    margin-top: 10px;
    font-size: 14px;
    color: #44b883;
  }
}
</style>